package qs.openxt.libs.remoting;

import com.alibaba.fastjson.JSONObject;

import org.xutils.http.RequestParams;
import org.xutils.x;

import java.net.HttpURLConnection;
import java.util.Iterator;
import java.util.Map;

import qs.openxt.libs.util.StringUtil;

/**
 * 通过Http方式与IME服务器进行通讯的工具类
 *
 * @author honghao
 */
public class Client {
	private String METHOD_POST = "POST";

	private final static String ENCODING = "utf-8";

	public static final String STATUS_OK = "OK";
	public static final String STATUS_ERR = "error";
	public static final String ERR_MESSAGE = "message";

	private HttpURLConnection connection = null;

	private String serverAddress = "";
	private JSONObject header = null;

	public void setServerAddress(String serverAddress) {
		this.serverAddress = serverAddress;
	}

	public void close() {
		if (connection != null)
			connection.disconnect();
	}

	public void setMethod(String method) {
		METHOD_POST = method;
	}

	public void setHeader(JSONObject header) {
		this.header = header;
	}

	private String request(Map<String, String> args) throws Exception {
		RequestParams params = new RequestParams(serverAddress);
		params.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + ENCODING);
		if(header != null) {
			Iterator it = header.keySet().iterator();
			while (it.hasNext()) {
				String key = (String)it.next();
				params.addHeader(key, header.getString(key));
			}
		}
		for (Map.Entry<String, String> entry : args.entrySet()) {
			params.addQueryStringParameter(entry.getKey(), entry.getValue());
		}
		for (Map.Entry<String, String> entry : args.entrySet()) {
			params.addBodyParameter(entry.getKey(), entry.getValue());
		}

		try {
			if("POST".equals(METHOD_POST))
				return x.http().postSync(params, String.class);
			else
				return x.http().getSync(params, String.class);
		}catch (Throwable e){
			return null;
		}
	}

	private String request(String query) throws Exception {
		if (!StringUtil.isNull(query)) {
			serverAddress += "?" + query;
		}

		RequestParams params = new RequestParams(serverAddress);
		params.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + ENCODING);
		if(header != null) {
			Iterator it = header.keySet().iterator();
			while (it.hasNext()) {
				String key = (String)it.next();
				params.addHeader(key, header.getString(key));
			}
		}

		try {
			if("POST".equals(METHOD_POST))
				return x.http().postSync(params, String.class);
			else
				return x.http().getSync(params, String.class);
		}catch (Throwable e){
			return null;
		}
	}

	public String request(Object args) throws Exception {
		if (args != null && args instanceof Map) {
			Map<String, String> data = (Map<String, String>) args;
			return request(data);
		}

		String param = args == null ? null : args.toString();
		return request(param);
	}
}
